#pragma once


#include<iostream>

using namespace std;

template<class K>
struct BSTNode
{
	K _key;
	BSTNode<K>* _left;
	BSTNode<K>* _right;

	BSTNode(const K& key)
		:_key(key)
		, _left(nullptr)
		, _right(nullptr)
	{ }
};

template<class K>
class BSTree
{
	typedef BSTNode<K> Node;
public:
	bool insert(const K& key)
	{
		if (_root == nullptr)
		{
			_root = new Node(key);
			return true;
		}
		Node* pcur = _root;
		Node* parent = nullptr;
		while (pcur)
		{
			if (key > pcur->_key)
			{
				parent = pcur;
				pcur = pcur->_right;
			}
			else if (key < pcur->_key)
			{
				parent = pcur;
				pcur = pcur->_left;
			}
			else
			{
				return false;
			}
		}
		pcur = new Node(key);
		if (key > parent->_key)
		{
			parent->_right = pcur;
		}
		else
		{
			parent->_left = pcur;
		}
		return true;
	}

	bool Find(const K& key)
	{
		Node* pcur = _root;
		Node* parent = nullptr;
		while (pcur)
		{
			if (key > pcur->_key)
			{
				parent = pcur;
				pcur = pcur->_right;
			}
			else if (key < pcur->_key)
			{
				parent = pcur;
				pcur = pcur->_left;
			}
			else
			{
				return true;
			}
		}
		return false;
	}

	bool Erase(const K& key)
	{
		Node* pcur = _root;
		Node* parent = nullptr;
		while (pcur)
		{
			if (key > pcur->_key)
			{
				parent = pcur;
				pcur = pcur->_right;
			}
			else if (key < pcur->_key)
			{
				parent = pcur;
				pcur = pcur->_left;
			}
			else
			{
				if (pcur->_left == nullptr)
				{
					if (pcur == _root)
					{
						_root = pcur->_right;
					}
					else
					{
						if (pcur == parent->_left)
						{
							parent->_left = pcur->_right;
						}
						else
						{
							parent->_right = pcur->_right;
						}
					}
					delete pcur;
				}
				else if (pcur->_right == nullptr)
				{
					if (pcur == _root)
					{
						_root = pcur->_left;
					}
					else
					{
						if (pcur == parent->_left)
						{
							parent->_left = pcur->_left;
						}
						else
						{
							parent->_right = pcur->_left;
						}
					}
					delete pcur;
				}
				else
				{
					Node* replace = pcur->_left;
					Node* ReplaceParent = pcur;
					while (replace->_left)
					{
						ReplaceParent = replace;
						replace = replace->_left;
					}
					swap(pcur->_key, replace->_key);
					if (ReplaceParent->_left == replace)
					{
						ReplaceParent->_left = replace->_right;
					}
					else
					{
						ReplaceParent->_right = replace->_right;
					}
					delete replace;
				}
				return true;
			}
		}
		return false;
	}

	void _InOrder(Node* root)
	{
		if (root == nullptr)
		{
			return;
		}
		_InOrder(root->_left);
		cout << root->_key << ' ';
		_InOrder(root->_right);
	}

	void InOrder()
	{
		_InOrder(_root);
		cout << endl;
	}

private:
	Node* _root = nullptr;
};